package com.example.aop;

import com.example.anno.CheckRepeat;
import com.example.exception.RepeateException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Aspect
@Component

public class CodeAop {
    @Autowired
    private RedisTemplate redisTemplate;
    @Before("@annotation(checkRepeat)")
    public  void before( CheckRepeat checkRepeat)
    {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = sra.getRequest();
        String clientid= req.getParameter("clientid");
        if(checkRepeat.save())
        {
            UUID u= UUID.randomUUID();
            String repeatToken= u.toString();
            req.setAttribute("repeatToken",repeatToken);
            redisTemplate.opsForValue().set(clientid,repeatToken,10, TimeUnit.MINUTES);
        }

        if(checkRepeat.repeat())
        {
            String repeatToken= (String) redisTemplate.opsForValue().get(clientid);
            String repeatToken1=req.getParameter("repeatToken");
            if(null==repeatToken || repeatToken.length()==0 ||  !repeatToken1.equals(repeatToken))
            {
                throw  new RepeateException();
            }
        }
    }

    @After("@annotation(checkRepeat)")
    public  void after( CheckRepeat checkRepeat)
    {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = sra.getRequest();
        String clientid= req.getParameter("clientid");
        if(checkRepeat.repeat())
            redisTemplate.opsForValue().getOperations().delete(clientid);
    }

}
